package com.binfast.app.admin.services.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.binfast.app.admin.services.AdminUserServ;
import com.binfast.bean.dto.adminUser.AdminUserDetailDTO;
import com.binfast.bean.dto.adminUser.AdminUserGeneratePasswordDTO;
import com.binfast.bean.dto.adminUser.AdminUserListDTO;
import com.binfast.common.constant.enums.DeletedStatus;
import com.binfast.bean.model.auth.AdminUser;
import com.binfast.bean.model.auth.AdminUserRole;
import com.binfast.bean.params.DetailParam;
import com.binfast.bean.params.adminUser.AdminUserDetailSaveParam;
import com.binfast.bean.params.adminUser.AdminUserListParam;
import com.binfast.bean.params.adminUser.AdminUserModifyPasswordParam;
import com.binfast.common.exception.PlatformException;
import com.binfast.seed.base.BaseService;
import com.binfast.service.dao.auth.AdminUserDao;
import com.binfast.service.dao.auth.AdminUserRoleDao;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminUserServImpl extends BaseService implements AdminUserServ {
    private static final Log log = LogFactory.get();

    @Autowired
    AdminUserDao adminUserDao;

    @Autowired
    AdminUserRoleDao adminUserRoleDao;

    @Override
    public AdminUserListDTO findList(AdminUserListParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",param.getKey());
        condition.put("enable",param.getIsEnable());
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort());
        pageQuery.setParas(condition);
        adminUserDao.findListPage(pageQuery);
        return new AdminUserListDTO(pageQuery.getList(),pageQuery.getTotalRow(),pageQuery.getPageNumber());
    }

    @Override
    public AdminUserDetailDTO findDetail(DetailParam param) {
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(param.getId());
        List<Long> roleIds = adminUserRoleDao.findRoleIdByUserIdAndUndeleted(adminUser.getId());
        adminUser.setRoleIds(roleIds);
        return new AdminUserDetailDTO(adminUser);
    }

    @Override
    @CachePut(cacheNames = "adminUser",value = "adminUser",key = "#param.adminUser.id")
    public AdminUser saveOne(AdminUserDetailSaveParam param) {
//        if(getCurrentUser()==null) throw new PlatformException("用户不存在");
        AdminUser adminUser = param.getAdminUser();
        List<Long> roleIds = param.getRoleIds();
        setBaseInfo(adminUser);
        if(Convert.toLong(adminUser.getId(),0l) <= 0) {
            adminUser.setPassword(SecureUtil.md5(param.getPassword()));
            adminUserDao.insertTemplate(adminUser,true);
        } else {
            adminUserDao.updateTemplateById(adminUser);
            adminUserRoleDao.deleteByUserId(adminUser.getId(),getCurrentUser(AdminUser.class).getId());
        }
        List<AdminUserRole> adminUserRoleList = new ArrayList<>();
        if(roleIds!=null && roleIds.size()>0){
            for(Long roleId : roleIds){
                AdminUserRole userRole = new AdminUserRole();
                userRole.setAdminUserId(adminUser.getId());
                userRole.setAdminRoleId(roleId);
                setBaseInfo(userRole);
                adminUserRoleList.add(userRole);
            }
            adminUserRoleDao.insertBatch(adminUserRoleList);
        }
        return adminUser;
    }

    @Override
    @CachePut(cacheNames = "adminUser",value = "adminUser",key = "#param.adminUser.id")
    public AdminUser savePassword(AdminUserModifyPasswordParam param) {
        AdminUser adminUser = param.getAdminUser();
        if(adminUser== null) throw new PlatformException("用户不存在");
        setBaseInfo(adminUser);
        adminUser.setPassword(SecureUtil.md5(param.getPassword()));
        adminUserDao.updateTemplateById(adminUser);
        return adminUser;
    }

    @Override
    public AdminUserGeneratePasswordDTO generatePassword(DetailParam param) {
        AdminUser adminUser = new AdminUser();
        adminUser.setId(param.getId());
        String password =  RandomUtil.randomString(8);
        setBaseInfo(adminUser);
        adminUser.setPassword(SecureUtil.md5(password));
        adminUserDao.updateTemplateById(adminUser);
        return new AdminUserGeneratePasswordDTO(password);
    }

    @Override
    public Long deleteOne(DetailParam param) {
        Long id = param.getId();
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(id);
        if(adminUser == null) throw new PlatformException("用户已不存在");
        adminUser.setDeleted(DeletedStatus.DELETED);
        setBaseInfo(adminUser);
        adminUserDao.updateTemplateById(adminUser);
        adminUserRoleDao.deleteByUserId(id,getCurrentUser(AdminUser.class).getId());
        return id;
    }

    @Override
    public Long isEnableOne(DetailParam param) {
        Long id = param.getId();
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(id);
        if(adminUser == null) throw new PlatformException("用户已不存在");
        setBaseInfo(adminUser);
        adminUser.setIsEnable(param.getIsEnable());
        adminUserDao.updateTemplateById(adminUser);
        return id;
    }

    @Override
    @Cacheable(cacheNames = "adminUser",value = "adminUser",key = "#id")
    public AdminUser getAdminUser(Long id) {
        log.info("---- 没有缓存，读取数据库 ---------");
        return adminUserDao.findByIdAndDeleted(id);
    }
}
